package main;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;

import dataAccess.databaseManagement.entity.AssetEntity;
import dataAccess.databaseManagement.entity.PriceEntity;
import dataAccess.databaseManagement.manager.AssetManager;
import dataAccess.databaseManagement.manager.PriceManager;

public class TestMatching {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		AssetEntity asset = new AssetManager().getAssetBySymbolAndExchange("^VNINDEX", "INDEX");
		ArrayList<PriceEntity> priceList = new PriceManager().getPriceByAssetID(asset.getAssetID());
		
		BufferedWriter bufferedWriterResult = new BufferedWriter(
				new FileWriter(new File("vnIndex.csv")));

		bufferedWriterResult.write("Date, ClosePrice");
		bufferedWriterResult.newLine();		
		for (PriceEntity price : priceList) {
			bufferedWriterResult.write(price.getDate() + "," + price.getClose());
			bufferedWriterResult.newLine();
		}
		
		bufferedWriterResult.close();
		
		MatchingAlgorithm matchingAlgorithm = new MatchingAlgorithm();
		matchingAlgorithm.setPriceEntities(priceList);
		matchingAlgorithm.setInterval(20);
		matchingAlgorithm.setNoSample(3);
		
		double[][] matchings = new double[5][];
		double min = Double.MAX_VALUE;
		
		for (int i = findIndex(2009, 10, 23, priceList); i < findIndex(2010, 11, 22, priceList); ++i) {
			double[][] matchingsTemp = matchingAlgorithm.findTheBestFit(i);
			if (matchingsTemp[4][3] < min) {
				min = matchingsTemp[4][3];
				matchings = matchingsTemp;
			}
		}

		bufferedWriterResult = new BufferedWriter(
				new FileWriter(new File("vnIndexMatching.csv")));
		
		for (int j = 0; j < matchings.length-1; ++j) {
			double[] pair = matchings[j];
			int begin = (int) pair[0];
			int end = (int) pair[1];

			for (int i = begin; i <= end; ++i) {
				bufferedWriterResult.write(priceList.get(i).getDate() + "," + priceList.get(i).getClose());
				bufferedWriterResult.newLine();
			}
			
			bufferedWriterResult.newLine();
			bufferedWriterResult.newLine();
		}
		
		for (double distance : matchings[matchings.length-1]) {
			System.out.println(distance);
		}
		
		bufferedWriterResult.close();
	}
	
	public static int findIndex(int year, int month, int day, ArrayList<PriceEntity> priceList) {
		Calendar calendar = Calendar.getInstance();
		
		calendar.set(year, month-1, day);
		Date date = new Date(calendar.getTime().getTime());

		int i = 0;
		while (i < priceList.size() && priceList.get(i).getDate().before(date)) {
			i++;
		}
		return i;
	}


}
